package com.sjl.hutool;


import java.util.concurrent.*;

public class ExecutorTest {

    // 定义线程池，推荐手动创建线程池： https://blog.csdn.net/LLLLLiSHI/article/details/88057655
    private static ExecutorService pool = Executors.newFixedThreadPool(1);

    /**
     *  jdk的api：Future类已经提供满足的api
     */
    public static void main(String[] args) {
        System.out.println("主程序执行开始……");
        //定义线程
        Callable<String> call = () -> {
            // 设置2秒睡眠
            TimeUnit.SECONDS.sleep(5);
            System.out.println("sss");
            return "这是线程执行结果……";
        };

        // 手动控制线程
        Future<String> result = pool.submit(call);
        try {
            // 如果在超时时间内，没有数据返回：则抛出TimeoutException异常
            String callResult = result.get(2, TimeUnit.SECONDS);
            System.out.println(callResult);
        } catch (InterruptedException e) {
            System.out.println("InterruptedException发生");
        } catch (ExecutionException e) {
            System.out.println("ExecutionException发生");
        } catch (TimeoutException e) {
            System.out.println("TimeoutException发生，意味着线程超时报错");
            pool.shutdownNow();
        }
        System.out.println("主程序执行完成……");

    }

}
